let currentDate = new Date();

// 初始化
window.addEventListener('load', function() {
    const input = document.getElementById('date-input');
    const typeSelect = document.getElementById('input-type');
    const clearBtn = document.getElementById('clear-btn');
    
    if (!input || !typeSelect) {
        console.error('找不到输入元素');
        return;
    }
    
    // 输入框留空，立即显示当前时间
    currentDate = new Date();
    updateResults(currentDate);
    
    // 监听输入变化
    input.oninput = function() {
        toggleClearButton();
        handleInput();
    };
    
    typeSelect.onchange = function() {
        handleInput();
    };
    
    // 每秒更新一次当前时间（仅当输入框为空时）
    setInterval(() => {
        if (!input.value.trim()) {
            currentDate = new Date();
            updateResults(currentDate);
        }
    }, 1000);
});

function toggleClearButton() {
    const input = document.getElementById('date-input');
    const clearBtn = document.getElementById('clear-btn');
    
    if (input.value.trim()) {
        clearBtn.classList.add('show');
    } else {
        clearBtn.classList.remove('show');
    }
}

function clearInput() {
    const input = document.getElementById('date-input');
    input.value = '';
    toggleClearButton();
    currentDate = new Date();
    updateResults(currentDate);
}

function handleInput() {
    const input = document.getElementById('date-input').value.trim();
    const type = document.getElementById('input-type').value;
    
    if (!input) {
        currentDate = new Date();
        updateResults(currentDate);
        return;
    }
    
    try {
        let date;
        
        if (type === 'auto') {
            // 自动识别
            if (/^\d+$/.test(input)) {
                // 纯数字，判断是秒还是毫秒
                const num = parseInt(input);
                if (num > 10000000000) {
                    date = new Date(num); // 毫秒
                } else {
                    date = new Date(num * 1000); // 秒
                }
            } else {
                date = new Date(input);
            }
        } else if (type === 'timestamp') {
            date = new Date(parseInt(input));
        } else if (type === 'timestamp-sec') {
            date = new Date(parseInt(input) * 1000);
        } else {
            date = new Date(input);
        }
        
        if (isNaN(date.getTime())) {
            throw new Error('无效的日期');
        }
        
        currentDate = date;
        updateResults(date);
    } catch (err) {
        console.error('解析日期失败:', err);
    }
}

function updateResults(date) {
    const results = [
        {
            label: 'JS 本地日期字符串',
            value: date.toLocaleString('zh-CN', { 
                timeZone: 'Asia/Shanghai',
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            }) + ' (中国标准时间)'
        },
        {
            label: 'ISO 8601',
            value: date.toISOString()
        },
        {
            label: 'ISO 9075',
            value: formatISO9075(date)
        },
        {
            label: 'RFC 3339',
            value: date.toISOString()
        },
        {
            label: 'RFC 7231',
            value: date.toUTCString()
        },
        {
            label: 'Unix 时间戳（秒）',
            value: Math.floor(date.getTime() / 1000).toString()
        },
        {
            label: '时间戳（毫秒）',
            value: date.getTime().toString()
        },
        {
            label: 'UTC 格式',
            value: date.toUTCString()
        },
        {
            label: 'Mongo ObjectID',
            value: generateMongoObjectId(date)
        },
        {
            label: 'Excel 日期时间',
            value: dateToExcel(date).toString()
        }
    ];
    
    const resultsContainer = document.getElementById('results');
    resultsContainer.innerHTML = results.map(item => `
        <div class="result-item">
            <div class="result-label">${item.label}</div>
            <div class="result-value">${item.value}</div>
            <button class="copy-btn" onclick="copyResult('${escapeForAttribute(item.value)}', this)">
                📋
            </button>
        </div>
    `).join('');
}

function formatISO9075(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function generateMongoObjectId(date) {
    const timestamp = Math.floor(date.getTime() / 1000).toString(16);
    const rest = '0'.repeat(16);
    return timestamp + rest;
}

function dateToExcel(date) {
    // Excel 日期从 1900-01-01 开始计算
    const excelEpoch = new Date(1899, 11, 30);
    const diff = date.getTime() - excelEpoch.getTime();
    const days = diff / (1000 * 60 * 60 * 24);
    return days.toFixed(11);
}

function escapeForAttribute(str) {
    return str.replace(/'/g, "\\'").replace(/"/g, '&quot;');
}

async function copyResult(text, button) {
    try {
        await navigator.clipboard.writeText(text);
        button.textContent = '✓';
        button.classList.add('copied');
        setTimeout(() => {
            button.textContent = '📋';
            button.classList.remove('copied');
        }, 1500);
    } catch (err) {
        console.error('复制失败:', err);
    }
}
